package com.killer.leaf.controller;


import com.killer.common.entity.Result;
import com.killer.leaf.exception.LeafServerException;
import com.killer.leaf.service.IDGenService;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/snowflake")
@ApiModel("雪花算法生成id")
public class SnowFlakeController {

    @Autowired
    private IDGenService idGenService;

    @RequestMapping("/getId")
    @ApiModelProperty("获取单个id")
    public Result<Long> getId() {
        long id = idGenService.get();
        if (id < 0) {
            throw new LeafServerException("id获取异常,异常id的值为"+id);
        }
        return Result.success(id);
    }

    @RequestMapping("/getBatch")
    @ApiModelProperty("批量获取id")
    public Result<List<Long>> getBatch(@RequestParam(value = "batch")Integer batch) {
        if (batch <= 0) {
            throw new RuntimeException("批量必须大于0");
        }
        List<Long> idList = new ArrayList<>();
        for (int i = 0; i < batch; i++) {
            long id = idGenService.get();
            if (id < 0) {
                throw new LeafServerException("id获取异常,异常id的值为"+id);
            }
            idList.add(id);
        }
        return Result.success(idList);
    }

}
